﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace DEMO.Y2015CS58.UI
{
    public partial class frmDemoDataProvider : Form
    {
        public frmDemoDataProvider()
        {
            InitializeComponent();
        }

        private void btnShowData_Click(object sender, EventArgs e)
        {
            //1. Khai báo kết nối
            SqlConnection conn = new SqlConnection("Data Source=D630;Initial Catalog=XUATNHAPTON;Persist Security Info=True;User ID=sa;Password=123456");

            //2.SqlCommand
            SqlCommand cmd = new SqlCommand("SELECT * FROM KHACHHANG", conn);


            //3. Khai báo Adapter
            SqlDataAdapter da = new SqlDataAdapter(cmd);

            DataTable dt = new DataTable();

            da.Fill(dt);

            dataGridView1.DataSource = dt;
        }

        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            //1. Khai báo kết nối
            SqlConnection conn = new SqlConnection("Data Source=D630;Initial Catalog=XUATNHAPTON;Persist Security Info=True;User ID=sa;Password=123456");

            try
            {
                //Mở kết nối
                conn.Open();
                //
                //
                //
                MessageBox.Show("Kết nối thành công");

                //LÀm các thao tấc với dữ liệu
                //
                //
            }
            catch (SqlException ex)
            {
                MessageBox.Show("Kết nối cơ sử dữ liệu thất bại.");
            }
            finally
            {
                conn.Close();
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            //1. Khai báo kết nối
            SqlConnection conn = new SqlConnection("Data Source=D630;Initial Catalog=XUATNHAPTON;Persist Security Info=True;User ID=sa;Password=123456");

            //2. Command
            string sql = String.Format("INSERT INTO KHACHHANG (MaKH,TenKH) VALUES ('{0}',N'{1}')", txtMaKH.Text, txtTenKH.Text);

            SqlCommand cmd = new SqlCommand(sql, conn);

            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();

            btnShowData.PerformClick();
        }


    }
}
